#Python's pattern matching
Pattern matching is a grammatical structure that checks whether a variable matches a certain pattern, controlled by match
and case
.
# The patterns are checked in order, and only the first matching pattern is executed.
match variable:
case pattern-1:
code-block-1
case pattern-2:
code-block-2
...
case pattern-n:
code-block-n
#Exact matching
The pattern is an exact value, and the variable matches if it is equal to the pattern. For example:
value:int = int(input("Please press 1 for a positive review, press 2 for a negative review, and press 3 for a complaint:"))
match value:
case 1:
print("positive review")
case 2:
print("negative review")
case 3:
print("complaint")
case _: # Unconditional match
print("Invalid input")
case _:
is a wildcard pattern that can match anything and is usually written last as the default action when all other patterns do not match.
#Type matching
The pattern is a type, and the variable matches if it matches that type. For example:
value:str = "233"
match value:
case int(x): # When matching, value will be assigned to x
print("The type is integer and the value is", x)
case str(x):
print("The type is string and the value is", x)
#Condition matching
The pattern is a conditional expression, and the variable matches when it satisfies the expression. For example:
age:int = int(input("Please enter your age:"))
match age:
case x if x < 3: # When matching, value will be assigned to x
print(x, "years old, baby")
case x if x < 18:
print(x, "years old, juvenile")
case x if x < 44:
print(x, "years old, youth")
case x if x < 59:
print(x, "years old, middle aged")
case x: # Unconditional match
print(x, "years old, elderly")